package org.dromara.module.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.TransactionalException;
import org.dromara.common.core.utils.OssUtil;
import org.dromara.common.core.utils.QRCodeUtilEx;
import org.dromara.module.domain.SplitAccount;
import org.dromara.module.domain.WxUser;
import org.dromara.module.mapper.SplitAccountMapper;
import org.dromara.module.mapper.SplitAccountRecordMapper;
import org.dromara.module.mapper.WxUserMapper;
import org.dromara.module.service.IWxUserService;
import org.dromara.system.domain.SysUser;
import org.dromara.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 小程序用户Service业务层处理
 *
 * @author Lion Li
 * @date 2025-04-01
 */
@RequiredArgsConstructor
@Service
public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUser> implements IWxUserService {

    @Resource
    private WxUserMapper userMapper;
    @Resource
    protected RedisTemplate<String, Object> redisTemplate;
    @Resource
    private SplitAccountMapper splitAccountMapper;
    @Resource
    private SplitAccountRecordMapper splitAccountRecordMapper;
    @Resource
    private ISysUserService sysUserService;

    @Value("${ruoyi.profile}")
    private String profile;

    @Override
    @Transactional
    public WxUser register(String openId, String unionId, String sessionKey, String token, String platform, double lng, double lat, String from_type, Integer userType) throws TransactionalException {
        WxUser user = new WxUser();
        int ret = 0;
        try {
            user.setOpenId(openId);
            user.setUnionId(unionId);
            user.setCreateTime(new Date());
            user.setLastActiveTime(new Date());
            user.setSessionKey(sessionKey);
            user.setUserType(userType);
            user.setIsAdmin(0);
            user.setToken(token);
            user.setLng(new BigDecimal(lng));
            user.setLat(new BigDecimal(lat));
            user.setPlatform(platform);
            user.setFaceUrl("https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132");

            ret = userMapper.insert(user);
            if (ret <= 0) {
                throw new TransactionalException("userMapper insert error");
            }

            Integer accountType = null;
            if (platform.equals("driver")) {
                accountType = 2;
            } else if (platform.equals("wxmini")) {
                accountType = 1;
            }
            if (accountType != null) {
                Long count = splitAccountMapper.selectCount(Wrappers.<SplitAccount>lambdaQuery()
                    .eq(SplitAccount::getUserId, user.getId()));
                if (count == 0) {
                    SplitAccount splitAccount = new SplitAccount();
                    splitAccount.setUserId(user.getId());
                    splitAccount.setFreeze(new BigDecimal(0));
                    ret = splitAccountMapper.insert(splitAccount);
                    if (ret <= 0) {
                        throw new TransactionalException("merMapper insert error");
                    }
                }
            }


            String userNo = "25" + String.format("%06d", user.getId());
            user.setNickName("用户" + user.getId());
            user.setUserNo(userNo);
            ret = userMapper.updateById(user);
            if (ret <= 0) {
                throw new TransactionalException("userMapper insert error");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new TransactionalException("register system error");
        }
        return user;
    }

    @Override
    @Transactional
    public int bandPhone(String phone, WxUser user, String platform) throws TransactionalException {
        try {
            int ret = 0;
            Map<String, Object> map = new HashMap<>();
            map.put("userType", user.getUserType());
            map.put("phoneNum", phone);
            user.setPhoneNum(phone);

            //处理绑定商户、骑手信息///////////////
            SysUser sysUser = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getPhonenumber, phone)
                .eq(SysUser::getStatus, 0).last("limit 1"));
            if (sysUser != null) {
                //用户类型 0 - 普通用户  1 - 商家用户  2 - 骑手 3 - 无人机起飞端  4 - 无人机返航端
                if (platform.equals("service")) {//商户
                    //将SysUserId绑定到小程序账号
                    user.setSysUserId(sysUser.getUserId().intValue());
                    user.setUserType(1);
                } else if (platform.equals("driver")) {//配送端
                    //将SysUserId绑定到小程序账号
                    user.setSysUserId(sysUser.getUserId().intValue());
                    if (sysUser.getUserType().equals("rider")) {
                        user.setUserType(2);
                    } else if (sysUser.getUserType().equals("uav_begin")) {
                        user.setUserType(3);
                    } else if (sysUser.getUserType().equals("uav_end")) {
                        user.setUserType(4);
                    } else if (sysUser.getUserType().equals("student")) {
                        user.setUserType(5);
                    }
                }
            } else { // 商户 骑手没有sys_user不允许登录
                if (platform.equals("service") || platform.equals("driver")) {
                    return -1;
                }
            }
            /////////////////////////////

            ret = userMapper.updateById(user);
            if (ret <= 0) {
                throw new TransactionalException("userMapper updateById  error");
            }

            return ret;
        } catch (TransactionalException ex) {
            throw new TransactionalException("bandShop system error");
        }
    }

    @Override
    public int unBandPhone(String phone, WxUser user) throws TransactionalException {
        try {
            int ret = 0;
            Map<String, Object> map = new HashMap<>();
            map.put("userType", user.getUserType());
            map.put("phoneNum", phone);

            user.setPhoneNum("");
            ret = userMapper.updateById(user);
            if (ret <= 0) {
                throw new TransactionalException("userMapper updateById  error");
            }
            return ret;
        } catch (TransactionalException ex) {
            throw new TransactionalException("bandShop system error");
        }
    }

    @Override
    public List<WxUser> selectByShopId(Integer shop_id, Integer user_id, Integer offset, Integer pageSize, Date begin_time, Date end_time) {
        return null;//userMapper.selectByShopId(shop_id,user_id,offset,pageSize,begin_time,end_time);
    }

    @Override
    @Transactional
    public int updateLogin(WxUser user) throws TransactionalException {
        int ret = 0;
        try {

            String userNo = "25" + String.format("%06d", user.getId());
            user.setUserNo(userNo);
            if (StrUtil.isEmpty(user.getNickName())) {
                user.setNickName("用户" + user.getId());
            }
            ret = userMapper.updateById(user);
            if (ret <= 0) {
                throw new TransactionalException("userMapper insert error");
            }

            QueryWrapper<SplitAccount> qwAccount = new QueryWrapper<>();
            qwAccount.eq("user_id", user.getId());
            qwAccount.last("limit 1");
            SplitAccount splitAccount = splitAccountMapper.selectOne(qwAccount);
            if (splitAccount == null) {
                splitAccount = new SplitAccount();
                splitAccount.setUserId(user.getId());
                splitAccount.setFreeze(new BigDecimal(0));
                ret = splitAccountMapper.insert(splitAccount);
                if (ret <= 0) {
                    throw new TransactionalException("splitAccountMapper insert error");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new TransactionalException("updateLogin system error");
        }
        return ret;
    }

}
